<template>
  <el-dialog title="物资入库" :visible.sync="localVisible" @close="closeDialog">
    <el-form :model="form">
      <el-form-item label="入库设备数量">
        <el-input-number v-model="form.quantity" @change="generateDeviceCodes" :min="1"></el-input-number>
      </el-form-item>
      <div v-for="(code, index) in form.deviceCodes" :key="index">
        <el-form-item :label="'设备编码' + (index + 1)">
          <el-input v-model="form.deviceCodes[index]" :class="{ 'error-input': !form.deviceCodes[index] }"
            placeholder="请输入设备编码"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="confirmStorage">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import axios from 'axios'
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      form: {
        quantity: 1,
        deviceCodes: ['']
      },
      localVisible:this.visible
    };
  },
  watch: {
    visible(val) {
      this.localVisible = val;
    },
    localVisible(val) {
      this.$emit('update:visible', val);
    }
  },
  methods: {
    closeDialog() {
      this.localVisible = false;
      this.dialogVisible = false;
    },
    generateDeviceCodes() {
      this.form.deviceCodes = Array.from({ length: this.form.quantity }, () => '');
    },
    confirmStorage() {
      const allFilled = this.form.deviceCodes.every(code => code);
      if (!allFilled) {
        this.$message.error('所有设备编码为必填项');
        return;
      }
      // 发送入库请求
      console.log(this.form.deviceCodes)
      try {
        axios.post('/api/inventory/storageAdd', this.form.deviceCodes, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        this.$message.success('入库成功')
      } catch (error) {
        console.log(error)
        this.$message.error("入库失败")
      }


      this.closeDialog();
    }
  }
};
</script>

<style>
.error-input {
  border-color: red;
}
</style>